import backtrader as bt
import backtrader.indicators as btind
import talib


class Screener_SMA(bt.Analyzer):
    params = (('period',20), ('devfactor',2),)

    # def start(self):
    def __init__(self):
        bband = btind.BollingerBands(self.data.close,
                period=self.params.period, devfactor=self.params.devfactor)
        rvol= self.data.volume/btind.SMA(self.data.volume, period=self.p.period)
        
        rsi=btind.RSI_SMA(self.data.close, period=self.p.period)
        # rsi= talib.RSI(self.data.close, timeperiod=self.p.period)
        atr= btind.AverageTrueRange(self.data.close, period=self.p.period)
        
        sideway_conds=[]
        sideway_conds.append(bband.lines.top- bband.lines.bot < 0.1*self.data.close)
        sideway_conds.append(rsi > 30)
        sideway_conds.append(rsi < 70)
        sideway_conds.append(atr<0.05*self.data.close)
        sideway = bt.And(*sideway_conds)
        self.sideway = sideway(-1)
        self.stage1 = 0
        self.stage2 = False
        
        
        
    def next(self):
        if self.data.rvol>3 and self.data.close>self.data.close[-1] and self.sideway:
            
            self.rets.append({'date1':self.data.datetime.date()})
            self.stage1 +=1
            
        
        
        
        


    def stop(self):
        self.rets['over'] = list()
        self.rets['under'] = list()
        

def init_bbands(datas):
    dict_bb={data: bt.indicators.BollingerBands(data,
                                        period=20, devfactor=2)
     for data in datas}
    return dict_bb
                
class Screener_example(bt.Analyzer):
    params = (('period',20), ('devfactor',2),)

    def start(self):
        self.bband = {data: bt.indicators.BollingerBands(data,
                period=self.params.period, devfactor=self.params.devfactor)
                for data in self.datas}
        # self.bband =init_bbands(self.datas)

    def stop(self):
        self.rets['over'] = list()
        self.rets['under'] = list()

        for data, band in self.bband.items():
            node = data._name, data.close[0], round(band.lines.bot[0], 2)
            if data > band.lines.bot:
                self.rets['over'].append(node)
            else:
                self.rets['under'].append(node)
                





